import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/index.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _obscurePassword = true;

  // 添加焦点节点
  final FocusNode _usernameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 延迟执行，确保GoRouter已经完全初始化
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkForLoginCredentials();
    });
  }

  // 检查URL中是否包含登录凭据
  void _checkForLoginCredentials() {
    final router = GoRouter.of(context);
    final params = router.routeInformationProvider.value.uri.queryParameters;

    if (params.containsKey('username')) {
      _usernameController.text = params['username'] ?? '';
    }

    if (params.containsKey('password')) {
      _passwordController.text = params['password'] ?? '';
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _usernameFocusNode.dispose(); // 释放焦点节点
    _passwordFocusNode.dispose(); // 释放焦点节点
    super.dispose();
  }

  // 处理普通登录
  void _handleLogin() async {
    final username = _usernameController.text.trim();
    final password = _passwordController.text.trim();

    if (username.isEmpty || password.isEmpty) {
      EasyLoading.showInfo('Please enter username and password');
      return;
    }

    EasyLoading.show(status: 'Logging in...');

    // 短暂延迟模拟网络请求
    await Future.delayed(const Duration(milliseconds: 800));

    // 调用登录服务
    final user = UserService.login(username, password);

    if (user != null) {
      // 登录成功，设置当前用户
      await UserService.setCurrentUser(user);
      EasyLoading.showSuccess('Login successful');

      // 返回上一页或跳转到首页
      if (mounted) {
        final router = GoRouter.of(context);
        // 获取returnTo参数
        final returnTo =
            router
                .routeInformationProvider
                .value
                .uri
                .queryParameters['returnTo'];

        if (returnTo != null && returnTo.isNotEmpty) {
          // 如果有returnTo参数，则导航到指定页面
          router.go(returnTo);
        } else if (router.canPop()) {
          // 如果没有returnTo参数，但可以返回上一页，则返回上一页
          router.pop();
        } else {
          // 如果没有上一页，则返回首页
          router.go('/');
        }
      }
    } else {
      // 登录失败
      EasyLoading.showError('Invalid username or password');
    }
  }

  // 处理Apple登录
  void _handleAppleSignIn() async {
    try {
      EasyLoading.show(status: 'Connecting to Apple...');

      // 尝试进行Apple登录
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 获取到的Apple账号信息
      final appleId = credential.userIdentifier;
      final email = credential.email;
      final givenName = credential.givenName;
      final familyName = credential.familyName;

      // 实际应用中，这里应该调用后端API进行验证和账户关联
      // 这里仅做简单模拟
      if (appleId != null) {
        // 使用appleId作为账号查找用户
        var user = UserService.getUserByAccount(appleId);

        // 如果用户不存在，则注册一个
        if (user == null) {
          final nickname = (givenName ?? '') + (familyName ?? '');
          await UserService.register(appleId, 'apple_password');
          user = UserService.getUserByAccount(appleId);
        }

        if (user != null) {
          await UserService.setCurrentUser(user);
          EasyLoading.showSuccess('Login successful');

          if (mounted) {
            final router = GoRouter.of(context);
            // 获取returnTo参数
            final returnTo =
                router
                    .routeInformationProvider
                    .value
                    .uri
                    .queryParameters['returnTo'];

            if (returnTo != null && returnTo.isNotEmpty) {
              // 如果有returnTo参数，则导航到指定页面
              router.go(returnTo);
            } else if (router.canPop()) {
              // 如果没有returnTo参数，但可以返回上一页，则返回上一页
              router.pop();
            } else {
              // 如果没有上一页，则返回首页
              router.go('/');
            }
          }
        }
      } else {
        EasyLoading.showError('Apple login failed');
      }
    } catch (e) {
      print('Apple sign in error: $e');
      EasyLoading.showError('Apple login failed');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetsImages.splash),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),

                // 返回按钮和标题
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        // 使用GoRouter返回上一页，而不是Navigator.pop
                        final router = GoRouter.of(context);
                        if (router.canPop()) {
                          router.pop();
                        } else {
                          // 如果没有上一页，则返回首页
                          router.go('/');
                        }
                      },
                      child: Container(
                        width: 36.w,
                        height: 36.w,
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.3),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.arrow_back,
                          color: Colors.white,
                          size: 20.sp,
                        ),
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Text(
                      'Login',
                      style: TextStyle(
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),

                // 在中间部分添加Expanded包裹，确保内容可以滚动
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 169.h),

                        // 登录表单
                        Column(
                          children: [
                            // 用户名输入框
                            _buildTextField(
                              controller: _usernameController,
                              hintText: 'Input Username',
                              focusNode: _usernameFocusNode, // 设置焦点节点
                              nextFocusNode:
                                  _passwordFocusNode, // 设置下一个焦点节点为密码输入框
                            ),

                            SizedBox(height: 16.h),

                            // 密码输入框
                            _buildTextField(
                              controller: _passwordController,
                              hintText: 'Input Password',
                              isPassword: true,
                              obscureText: _obscurePassword,
                              onToggleObscure: () {
                                setState(() {
                                  _obscurePassword = !_obscurePassword;
                                });
                              },
                              focusNode: _passwordFocusNode, // 设置焦点节点
                              onSubmitted: _handleLogin, // 在最后一个输入框按回车键触发登录
                            ),

                            SizedBox(height: 16.h),

                            // 注册链接
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  "Don't have an account?",
                                  style: TextStyle(
                                    fontSize: 13.sp,
                                    color: Color(0xFF6B6B6B),
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                                TextButton(
                                  onPressed: () {
                                    context.push('/register');
                                  },
                                  style: TextButton.styleFrom(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8.w,
                                    ),
                                    minimumSize: Size.zero,
                                    tapTargetSize:
                                        MaterialTapTargetSize.shrinkWrap,
                                  ),
                                  child: Text(
                                    'Sign up',
                                    style: TextStyle(
                                      fontSize: 13.sp,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xFF150555),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),

                        SizedBox(height: 169.h),

                        // 登录按钮
                        SizedBox(
                          width: double.infinity,
                          height: 56.h,
                          child: ElevatedButton(
                            onPressed: _handleLogin,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Color(0xFFBD88FF),
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                              elevation: 0,
                              padding: EdgeInsets.symmetric(vertical: 16.h),
                            ),
                            child: Text(
                              'Login',
                              style: TextStyle(
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),

                        SizedBox(height: 16.h),

                        // Apple登录按钮
                        SizedBox(
                          width: double.infinity,
                          height: 56.h,
                          child: ElevatedButton(
                            onPressed: _handleAppleSignIn,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black,
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.r),
                              ),
                              elevation: 0,
                              padding: EdgeInsets.symmetric(vertical: 16.h),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.apple, size: 24.sp),
                                SizedBox(width: 8.w),
                                Text(
                                  'Continue with Apple',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w600,
                                    fontFamily: 'Inter',
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                // 服务条款和隐私政策
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 0),
                  child: SizedBox(
                    width: double.infinity,
                    child: Center(
                      child: FittedBox(
                        fit: BoxFit.scaleDown,
                        child: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: 'By Continuing you agree with',
                                style: TextStyle(
                                  color: const Color(0x991A1A1A),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              TextSpan(
                                text: ' ',
                                style: TextStyle(
                                  color: const Color(0xFF191919),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              TextSpan(
                                text: 'Terms of Service',
                                style: TextStyle(
                                  color: const Color(0xFF191919),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                  decoration: TextDecoration.underline,
                                ),
                              ),
                              TextSpan(
                                text: ' ',
                                style: TextStyle(
                                  color: const Color(0xFF191919),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              TextSpan(
                                text: '&',
                                style: TextStyle(
                                  color: const Color(0x991A1A1A),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              TextSpan(
                                text: ' ',
                                style: TextStyle(
                                  color: const Color(0xFF191919),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                              TextSpan(
                                text: 'Privacy Policy',
                                style: TextStyle(
                                  color: const Color(0xFF191919),
                                  fontSize: 12,
                                  fontFamily: 'Inter',
                                  fontWeight: FontWeight.w400,
                                  decoration: TextDecoration.underline,
                                ),
                              ),
                            ],
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    bool isPassword = false,
    bool? obscureText,
    VoidCallback? onToggleObscure,
    FocusNode? focusNode, // 添加焦点节点参数
    FocusNode? nextFocusNode, // 添加下一个焦点节点参数
    VoidCallback? onSubmitted, // 添加回车键提交回调参数
  }) {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: TextField(
        controller: controller,
        obscureText: isPassword ? (obscureText ?? true) : false,
        focusNode: focusNode, // 设置焦点节点
        onSubmitted: (_) {
          // 处理回车键事件
          if (nextFocusNode != null) {
            // 如果有下一个输入框，则跳转到下一个输入框
            FocusScope.of(context).requestFocus(nextFocusNode);
          } else if (onSubmitted != null) {
            // 如果没有下一个输入框，则执行提交回调
            onSubmitted();
          }
        },
        style: TextStyle(
          fontSize: 16.sp,
          color: Colors.white,
          fontWeight: FontWeight.w500,
          fontFamily: 'Inter',
        ),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            fontSize: 16.sp,
            color: Colors.white.withOpacity(0.8),
          ),
          contentPadding: EdgeInsets.symmetric(
            horizontal: 20.w,
            vertical: 18.h,
          ),
          border: InputBorder.none,
          suffixIcon:
              isPassword
                  ? IconButton(
                    icon: Icon(
                      obscureText ?? true
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                      color: Colors.white.withOpacity(0.7),
                      size: 22.sp,
                    ),
                    onPressed: onToggleObscure,
                  )
                  : null,
        ),
      ),
    );
  }
}
